package com.pengke.pangu.common.oss.qiniu;

import com.google.gson.Gson;
import com.pengke.pangu.common.config.QiniuConfig;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
public class QiniuUtil {

    @Resource
    private QiniuConfig qiniuConfig;

    public String upload(InputStream file, String key) throws QiniuException {
        // 构造一个带指定Zone对象的配置类, 注意这里的Zone.zone0需要根据主机选择
        Configuration cfg = Configuration.create(Region.autoRegion());
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成上传凭证，然后准备上传
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        String upToken = auth.uploadToken(qiniuConfig.getBuket());
        Response response = uploadManager.put(file, key, upToken, null, null);
        // 解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

        DownloadUrl url = new DownloadUrl(qiniuConfig.getDomain(), false, putRet.key);
        // 带有效期
//        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
//        long deadline = System.currentTimeMillis()/1000 + expireInSeconds;
//        return url.buildURL(auth,deadline);
        return url.buildURL();
    }

}

